package com.zrh.jsd.service.studydemo.local_persistence;

import com.zrh.jsd.common.model.UserRecord;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class ObjectSaveToFileTest {
    // 文件名可随意指定，你可以用文本编辑器打开这个文件（注意，记事本无法处理换行）
    static String filename = "D:/a/zrh.txt";

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        write();
        read();
    }

    public static <T> void write() throws IOException {
        File file = new File(filename);
        List<UserRecord> list = getUserList(10);
        Long start = System.currentTimeMillis();
        for (int i = 0; i < list.size(); i++) {
            FileOutputStream fos = new FileOutputStream(file, true);
            if (file.length() < 1) {
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(list.get(i));
                oos.close();
            } else {
                MyObjectOutputStream mos = new MyObjectOutputStream(fos);
                mos.writeObject(list.get(i));
                mos.close();
            }
        }


        System.out.println("over=================");

        System.out.println("耗时=====" + (System.currentTimeMillis() - start));
    }

    public static void read() {
        //测试读取
        List<UserRecord> list = new ArrayList<>();
        Long start = System.currentTimeMillis();
        try {
            FileInputStream fis = new FileInputStream(filename);
            ObjectInputStream ois = new ObjectInputStream(fis);
            while (fis.available() > 0) {//代表文件还有内容
                UserRecord userRecord = (UserRecord) ois.readObject();//从流中读取对象
                list.add(userRecord);
            }
            ois.close();//注意在循环外面关闭
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        System.out.println(list.size());
        System.out.println("耗时=====" + (System.currentTimeMillis() - start));
    }

    public static List<UserRecord> getUserList(int num) {
        List<UserRecord> userList = new ArrayList<>();
        String id = UUID.randomUUID().toString();
        for (int i = 0; i < num; i++) {
            userList.add(new UserRecord(id, id, id, id, i * 100, i * 100, new Date()));
        }
        return userList;
    }
}
